define(function(require) {
	var $ = require("jquery");
	var justep = require("$UI/system/lib/justep");

	var Model = function() {
		this.callParent();
		this.btnIndex = justep.Bind.observable('0'); // 菜单当前选中项
		this.setKeyShow = justep.Bind.observable('0'); // 菜单配置
		this.hasSubMenu = justep.Bind.observable(false); // 是否有子菜单
	};

	Model.prototype.modelParamsReceive = function(event) {
		this.groupName = this.getContext().getRequestParameter("groupName");
	};

	Model.prototype.toggleBtnClick = function(event) {
		// 左侧菜单切换设置
		var index = $(event.source.$domNode).index();
		this.btnIndex.set(index);
	};

	Model.prototype.getMouse = function() {
		var e = window.event;
		var scrollX = document.documentElement.scrollLeft || document.body.scrollLeft;
		var scrollY = document.documentElement.scrollTop || document.body.scrollTop;
		var x = e.pageX || e.clientX + scrollX;
		var y = e.pageY || e.clientY + scrollY;
		return {
			'x' : x,
			'y' : y
		};
	}

	Model.prototype.addBtnClick = function(event) {
		// 添加一级菜单
		var mouse = this.getMouse();
		var options = {};
		options.pageX = mouse.x;
		options.pageY = mouse.y;
		options.level = 1; // 一级
		options.type = 'add';// 新增
		this.showAddMenu(options);
	};

	Model.prototype.addSubMenuClick = function(event) {
		// 添加二级菜单
		window.event.stopPropagation();
		var mouse = this.getMouse();
		var options = {};
		options.pageX = mouse.x;
		options.pageY = mouse.y;
		options.level = 2; // 二级
		options.type = 'add';// 新增
		this.showAddMenu(options);
		this.subParentRow = event.bindingContext.$object;
	};

	Model.prototype.editeMenuClick = function(event) {
		// 修改一级菜单
		window.event.stopPropagation();
		var mouse = this.getMouse();
		var options = {};
		options.pageX = mouse.x;
		options.pageY = mouse.y;
		options.level = 1; // 一级
		options.type = 'edite';// 修改
		this.showAddMenu(options);
	};

	Model.prototype.editeSubMenuClick = function(event) {
		// 修改二级菜单
		window.event.stopPropagation();
		var mouse = this.getMouse();
		var options = {};
		options.pageX = mouse.x;
		options.pageY = mouse.y;
		options.level = 2; // 一级
		options.type = 'edite';// 修改
		this.showAddMenu(options);
	};

	Model.prototype.delMenuClick = function(event) {
		// 删除一级菜单
		window.event.stopPropagation();
		var id = this.subParentRow.val('id');
		this.comp('menuData').deleteData(event.bindingContext.$object);
		this.comp('subMenuData').eachAll(function(obj) {
			if (obj.row.val('parent') == id) {
				obj.data.deleteData(obj.row);
			}
		});
		this.setKeyShow.set(0);
		this.hasSubMenu.set(false);

	};

	Model.prototype.delSubMenuClick = function(event) {
		// 删除二级菜单
		window.event.stopPropagation();
		this.comp('subMenuData').deleteData(event.bindingContext.$object);
		this.setKeyShow.set(0);
		this.hasSubMenu.set(false);

	};

	Model.prototype.eventStop = function(event) {
		window.event.stopPropagation();
	};

	Model.prototype.showAddMenu = function(options) {
		// 显示添加菜单弹窗
		var $pop = $('[xid=popur]');
		var w = $pop.width();
		var h = $pop.height();
		var left = options.pageX;
		var top = options.pageY - h - 10;
		var left = options.pageX - (w / 2);
		var menuData = this.comp('menuData');
		var subData = this.comp('subMenuData');

		$pop.find('input').attr('level', options.level);
		$pop.find('input').attr('operate', options.type);

		if (options.type == "add") {
			this.comp('input1').clear();
			if (options.level == 1) {
				if (menuData.count() == 3) {
					justep.Util.hint("一级菜单数量不能超过3个", {
						'type' : 'warning'
					});
					return;
				}
				$pop.find('input').attr("placeholder", "一级菜单不多于4个汉字！");
			} else {
				var rows = subData.find([ 'parent' ], [ this.subParentRow.val('id') ]);
				if (rows.length == 5) {
					justep.Util.hint("二级级菜单数量不能超过5个", {
						'type' : 'warning'
					});
					return;
				}
				$pop.find('input').attr("placeholder", "二级菜单不多于7个汉字！");

			}
		} else {
			if (options.level == 1) {
				this.comp('input1').val(menuData.getCurrentRow().val('name'));
			} else {
				this.comp('input1').val(subData.getCurrentRow().val('name'));
			}
		}

		$pop.css({
			'left' : left,
			'top' : top,
			'display' : 'block'
		})

	}

	Model.prototype.popCancelBtnClick = function(event) {
		// 菜单弹窗取消按钮
		$('[xid=popur]').hide();
	};

	Model.prototype.popSureBtnClick = function(event) {
		// 菜单弹窗确认按钮
		var $input = $('[xid=popur]').find('input');
		var value = $input.val();
		var level = $input.attr('level');
		var operate = $input.attr('operate');
		var data = this.comp('menuData');
		var subData = this.comp('subMenuData');

		switch (level) {
		case "1":
			if (value.length == 0) {
				justep.Util.hint("请输入菜单名称", {
					'type' : 'warning'
				});
				$input.focus();
				return;
			}
			if (operate == "add") {
				data.newData();
				data.getLastRow().val('name', value);
				data.getLastRow().val('id', justep.UUID.createUUID());
			} else {
				data.getCurrentRow().val('name', value);
			}

			$('[xid=popur]').hide();
			break;
		case "2":
			if (value.length == 0) {
				justep.Util.hint("请输入菜单名称", {
					'type' : 'warning'
				});
				$input.focus();
				return;
			}
			if (operate == "add") {
				subData.newData();
				subData.getLastRow().val('name', value);
				subData.getLastRow().val('parent', this.subParentRow.val('id'));
				this.setKeyShow.set(1);
				this.hasSubMenu.set(true);
			} else {
				subData.getCurrentRow().val('name', value);
			}

			$('[xid=popur]').hide();

			break;
		}
	};

	Model.prototype.menuItemClick = function(event) {
		// 点击一级菜单
		var row = event.bindingContext.$object;
		var sub = this.comp('subMenuData').find([ 'parent' ], [ row.val('id') ], true, true, true);
		if (sub.length > 0) {
			this.hasSubMenu.set(true);
		} else {
			this.hasSubMenu.set(false);
		}
		this.checkedMenuItem(1);
		this.subParentRow = event.bindingContext.$object;
	};

	Model.prototype.subMenuItemClick = function(event) {
		// 点击子菜单
		var row = event.bindingContext.$object;
		this.subParentRow = event.bindingContext.$object;
		this.checkedMenuItem(2);
		this.hasSubMenu.set(false);
	};

	Model.prototype.checkedMenuItem = function(level) {
		$('.menu-list').find('.x-row').removeClass('active');
		$('.menu-list').find('.x-row').find('.js-show').hide();
		$(event.target).parent('.x-row').addClass('active');
		$(event.target).parent('.x-row').find('.js-show').show();
		this.setKeyShow.set(level);
	}

	Model.prototype.nowMenuBtnClick = function(event) {
		// 当前菜单
		this.getMenuData(event);
		$('[xid=nowMenuBtn]').addClass('active');
	};
	
	
	Model.prototype.getMenuData = function(event) {
		// 获取菜单数据
		var test;
		var sub = [];
		var self = this;
		event.source.set('disabled',true);
		$.ajax({
			type : "GET",
			contentType : "application/json;charset=UTF-8",
			dataType : "json",
			async : true,
			url : require.toUrl('/wxapi/mp/menus?group=' + this.groupName),
			success : function(resultData, textStatus, jqXHR) {
				test = resultData.data;
				for (var j = 0; j < test.length; j++) {
					test[j].id = j;
					if (test[j].hasOwnProperty('subButtons')) {
						for (var i = 0; i < test[j].subButtons.subButtons.length; i++) {
							test[j].subButtons.subButtons[i].parent = j;
							sub.push(test[j].subButtons.subButtons[i]);
						}
					}
				}

				self.comp('menuData').loadData(test);
				self.comp('subMenuData').loadData(sub);
				event.source.set('disabled',false);
			},
			error : function(err) {
				justep.Util.hint(JSON.parse(err.responseText).message, {
					"type" : "warning"
				});
				event.source.set('disabled',false);
			}
		});

	};

	Model.prototype.releaseBtnClick = function(event) {
		var menuData = this.comp('menuData');
		var subData = this.comp('subMenuData');
		var rows;
		var subButtons = [];
		var options = {
			buttons : [],
			group : this.groupName
		};
		menuData.eachAll(function(obj) {
			rows = subData.find([ 'parent' ], [ obj.row.val('id') ]);
			subButtons = [];
			if (rows.length > 0) {
				for (var i = 0; i < rows.length; i++) {
					subButtons.push(getOption(rows[i]));
				}
				options.buttons.push({
					"name" : obj.row.val('name'),
					"subButtons" : subButtons
				})
			} else {
				options.buttons.push(getOption(obj.row));
			}
		})
		
		event.source.set('disabled',true);
		
		// 提交菜单
		$.ajax({
			type : "POST",
			contentType : "application/json;charset=UTF-8",
			dataType : "json",
			async : true,
			url : require.toUrl('/wxapi/mp/menu'),
			data : JSON.stringify(options),
			success : function(res) {
				justep.Util.hint("菜单发布成功");
				event.source.set('disabled',false);
			},
			error : function(res) {
				justep.Util.hint("菜单发布失败，稍后重试", {
					"type" : "warning"
				});
				event.source.set('disabled',false);
			}
		});
	};

	var getOption = function(row) {
		var data = {};
		data.name = row.val('name');
		data.type = row.val('type');
		switch (row.val('type')) {
		case 'view':
			data.url = row.val('url');
			break;
		case 'click':
			data.key = row.val('key');
			break;
		case 'miniprogram':
			data.url = row.val('url');
			data.appid = row.val('appId');
			data.pagepath = row.val('pagePath');
			break;
		}

		return data;
	}

	return Model;
});